package com.googlecode.milib.tools {
	import com.googlecode.milib.service.singleton.EnterFrameService;

	import flash.events.Event;

	/**
	 * @author Marek Brun
	 */
	public class CallInNextFrame {
		
		static private var instance:CallInNextFrame;
		private var toCall:Array;
		private var efs:EnterFrameService;

		public function CallInNextFrame(access:Private) {
			toCall=[];
			efs=EnterFrameService.getInstance();
		}

		public function addMethod_(func:Function, aterFrames:uint=1):void {
			toCall.push([func, aterFrames]);
			efs.addEventListener(efs.event_EnterFrame, onEFS_EnterFrame);
		}
		
		static public function getInstance():CallInNextFrame {
			if(instance) { return instance; }
			else{ instance=new CallInNextFrame(null); return instance; }
		}
		
		static public function addMethod(func:Function, aterFrames:uint=1):void {
			getInstance().addMethod_(func, aterFrames);
		}
		
//********************************************************************************************
//		events for InNextFrame
//********************************************************************************************
		protected function onEFS_EnterFrame(event:Event):void {
			var i:uint;
			var loop:Array;
			for(i=0;i<toCall.length;i++){
				loop=toCall[i];
				loop[1]--;
				if(loop[1]==0){
					loop[0]();
					toCall.splice(i, 1); i--;
				}
			}
			if(!toCall.length){
				efs.removeEventListener(efs.event_EnterFrame, onEFS_EnterFrame);
			}
		}
		
	}
}
internal class Private {}